package com.ljd.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ljd.common.constant.ProductConstant;
import com.ljd.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.ljd.gulimall.product.entity.AttrGroupEntity;
import com.ljd.gulimall.product.entity.CategoryEntity;
import com.ljd.gulimall.product.service.AttrAttrgroupRelationService;
import com.ljd.gulimall.product.service.AttrGroupService;
import com.ljd.gulimall.product.service.CategoryService;
import com.ljd.gulimall.product.vo.Attr;
import com.ljd.gulimall.product.vo.AttrRespVo;
import com.ljd.gulimall.product.vo.AttrVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljd.common.utils.PageUtils;
import com.ljd.common.utils.Query;

import com.ljd.gulimall.product.dao.AttrDao;
import com.ljd.gulimall.product.entity.AttrEntity;
import com.ljd.gulimall.product.service.AttrService;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    AttrGroupService attrGroupService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);

        // 保存属性和属性分组关系
        if(attr.getAttrGroupId() != null && Objects.equals(attr.getAttrType(), 1)) {
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            relation.setAttrId(attrEntity.getAttrId());
            relation.setAttrGroupId(attr.getAttrGroupId());

            attrAttrgroupRelationService.save(relation);
        }

    }

    @Override
    public PageUtils baseQueryPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(catelogId != 0) {
            wrapper.eq("catelog_id",catelogId);
        }
        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)) {
            wrapper.and(ew -> {
                ew.eq("attr_id", key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );


        List<Long> catIds = page.getRecords().stream().map(AttrEntity::getCatelogId).collect(Collectors.toList());
        List<Long> attrIds = page.getRecords().stream().map(AttrEntity::getAttrId).collect(Collectors.toList());
        List<CategoryEntity> categoryEntities = new ArrayList<>();
        if(catIds.size() > 0) {
            categoryEntities = categoryService.list(new QueryWrapper<CategoryEntity>().in("cat_id", catIds));
        }
        List<AttrAttrgroupRelationEntity> relationEntities = new ArrayList<>();
        List<AttrGroupEntity> attrGroupEntities = new ArrayList<>();
        if(attrIds.size() > 0 && "base".equalsIgnoreCase(type)) {
            relationEntities = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_id", attrIds));
            if(relationEntities.size() >0) {
                attrGroupEntities = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().in("attr_group_id", relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrGroupId).collect(Collectors.toList())));
            }
        }

        List<CategoryEntity> finalCategoryEntities = categoryEntities;
        List<AttrAttrgroupRelationEntity> finalRelationEntities = relationEntities;
        List<AttrGroupEntity> finalAttrGroupEntities = attrGroupEntities;
        List<AttrRespVo> collect = page.getRecords().stream().map(p -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(p, attrRespVo);
            Long catId = p.getCatelogId();
            CategoryEntity categoryEntity = finalCategoryEntities.stream().filter(e -> Objects.equals(catId, e.getCatId())).findFirst().orElse(new CategoryEntity());
            attrRespVo.setCatelogName(categoryEntity.getName());
            Long attrId = p.getAttrId();
            Long attrGroupId = finalRelationEntities.stream().filter(e -> Objects.equals(e.getAttrId(), attrId)).map(AttrAttrgroupRelationEntity::getAttrGroupId).findFirst().orElse(null);
            if(attrGroupId != null) {
                AttrGroupEntity attrGroupEntity = finalAttrGroupEntities.stream().filter(e -> Objects.equals(e.getAttrGroupId(), attrGroupId)).findFirst().orElse(new AttrGroupEntity());
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());


        PageUtils utils = new PageUtils(page);
        utils.setList(collect);
        return utils;
    }

    @Override
    public AttrRespVo getAttr(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = baseMapper.selectById(attrId);
        if(attrEntity == null) {
            return null;
        }
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        Long catelogId = attrEntity.getCatelogId();
        if(catelogId != null) {
            CategoryEntity category = categoryService.getById(catelogId);
            attrRespVo.setCatelogName(category.getName());
            attrRespVo.setCatelogPath(categoryService.findParentId(catelogId));
        }

        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if(relationEntity != null) {
            Long attrGroupId = relationEntity.getAttrGroupId();
            AttrGroupEntity attrGroup = attrGroupService.getById(attrGroupId);
            attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
            attrRespVo.setGroupName(attrGroup.getAttrGroupName());
        }
        return attrRespVo;
    }

    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.baseMapper.updateById(attrEntity);
        Long attrGroupId = attr.getAttrGroupId();
        if(attrGroupId == null) {
            return;
        }
        int count = attrAttrgroupRelationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
        relation.setAttrGroupId(attrGroupId);
        relation.setAttrId(attr.getAttrId());
        if(count > 0) {
            // 修改
            attrAttrgroupRelationService.update(relation, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        } else {
            attrAttrgroupRelationService.save(relation);
        }
    }

    @Override
    public List<Attr> getSearchTypeAttr(List<Long> attrIds) {
        return baseMapper.getSearchTypeAttr(attrIds);
    }

}